<template>
    <div class="chat">
        <div class="leftHistorybox">
            <div class="newChatBtn" @click="openNewChat"><i class="el-icon-plus"></i>新聊天</div>
            <div class="chatBox">
                <!-- <div class="date">7天前</div> -->
                <div :class="[conversationId==item.id?'chatItemActive':'','chatItem']" v-for="(item,index) in historyList" :key="index">
                    <div class="name" @click="clickHistoryItem(item)">
                        <i class="el-icon-chat-square"></i>{{item.name}}
                    </div>
                    <div class="action">

                        <i class="el-icon-delete" @click="handleDelete(item)"></i>
                        <!-- <i class="el-icon-edit"></i> -->
                        <!-- <el-popconfirm title="删除后，该对话将不可恢复。确认删除吗？" class="deleteHistory" @confirm='handleDelete(item)'>
                            <i slot="reference" class="el-icon-delete"></i>
                        </el-popconfirm> -->
                    </div>
                </div>
            </div>
        </div>
        <div class="main-content">
            <div class="titleR1">
                <div>DeepSeek R1</div>
                <div>-满血版</div>
                <!-- <div>由文匠AI提供</div> -->
            </div>
            <div class="chatContentBox typeArea">
                <!-- <div class="typeArea"> -->
                <!-- {{ progressTxt }} -->
                <!-- <vue-markdown :source="progressTxt"></vue-markdown> -->
                <div class="chatContent">
                    <div v-for="(item,index) in dialogueList" :key="index">
                        <div class="rightBox">
                            <div class="contentBox">{{item.query}}</div>
                            <img class="via" src="../../assets/images/profilePhoto.png" alt="">
                        </div>
                        <div class="leftBox" v-if="item.answerThink">
                            <img class="via" src="../../assets/logo/logo.png" alt="">
                            <div class="contentBox">
                                <el-collapse v-model="item.collapseValue" :key="'think'+index">
                                    <el-collapse-item :title="item.answerText?'已深度思考':thinking" :name="'think'+index">
                                        <vue-markdown class="thinkBox" :source="item.answerThink"></vue-markdown>
                                    </el-collapse-item>
                                </el-collapse>
                                <vue-markdown class="textBox" :source="item.answerText"></vue-markdown>

                            </div>
                        </div>
                    </div>
                </div>
                <!-- {{dialogueList}} -->
                <!-- </div> -->
            </div>
            <div class="inputSendBox">
                <div class="typeArea">
                    <div class="inputBox">
                        <!-- <el-input  v-model="sendValue" placeholder="请输入问题，我可以完成智能解答、文案撰写、生成代码等多种任务..." @change="sendChat">
                        </el-input> -->

                        <el-input type="textarea" v-model="sendValue" resize="none" @keydown.native="handleKeyCode($event)"
                            placeholder="请输入问题，我可以完成智能解答、文案撰写、生成代码等多种任务...，按 Shift+Enter 换行">
                        </el-input>
                        <div class="btn">
                            <img v-if="loading" src="../../assets/images/tool/stop.png" alt="" @click="stopMessages">
                            <img v-else src="../../assets/images/tool/send.png" alt="" @click="sendChat">
                            <!-- <i class="el-icon-search" style="margin:3px 5px 0 0;font-size:20px" @click="searchTools"></i>
                        搜索模板 -->
                        </div>
                    </div>
                </div>
            </div>

        </div>

        <!-- 弹窗 -->
        <!-- <payMemberCard v-if="dialogPayMemberCard" @payEnd='payEnd'></payMemberCard> -->
    </div>
</template>

<script>
import toolBox from "@/api/toolBox";
import tools from '../components/tools'
import VueMarkdown from 'vue-markdown';
import { getToken } from '@/utils/auth'
import { fetchEventSource } from "@microsoft/fetch-event-source";
import { phoneLogin, sendSms, getUserInfo } from "@/api/login";
export default {
    name: 'PlanWriter',
    components: {
        VueMarkdown
    },
    data() {
        return {
            inputText: '',
            loading: false,
            tools: tools.tools,
            toolsItem: {},
            resultText: '',
            dialogPayMemberCard: false,
            sendAnswer: {},
            controller: null,
            progressDone: false,
            progressTxt: '',
            sendValue: '',
            userInfoDetail: {},
            conversationId: '',
            dialogueList: [],
            // dialogueList: [{ "type": "R", "text": "你好" }, { "type": "L", "text": "你好！有什么我可以帮助你的吗？", "think": "> 💭 好，用户发来了一句“你好”，这是中文里常见的问候语。首先，我需要确认用户的需求是什么。可能只是简单的打招呼，或者他们可能有后续的问题需要帮助。作为助理，我应该保持友好和开放的态度，鼓励他们进一步交流。\n\n> 接下来，我要考虑如何回应。中文的“你好”通常对应英文的“Hello”或“Hi”，所以直接回应“你好！有什么我可以帮助你的吗？”比较合适。这样的回答既礼貌又表明愿意提供帮助。\n\n> 另外，要检查有没有可能的深层需求。用户是否在测试我的响应速度或语言能力？或者他们可能在使用翻译工具，需要进一步的帮助？不过，目前的信息有限，不宜做过多假设。保持简洁和针对性是最好的策略。\n\n> 还要注意文化差异。在中文交流中，正式和非正式的问候有时区别不大，但作为AI，保持专业但亲切的语气比较重要。避免使用过于随意的俚语，保持中立和友好。\n\n> 最后，确保回应没有语法错误，符合中文表达习惯。可能需要检查标点符号是否正确，句子结构是否自然。比如，使用感叹号可以增加友好的感觉，而问句则邀请用户继续对话。\n\n> 总结一下，用户可能只是想打个招呼，或者准备提出具体问题。我的回应应友好，鼓励他们进一步说明需求，同时保持专业性。现在应该发送这样的回复：“你好！有什么我可以帮助你的吗？”\n> \n\n\n\n" }],
            loading: false,
            pushTextKey: 'answerThink',
            thinking: '思考中',
            thinkingTime: null,
            collapseValue: '',
            historyList: [],
        };
    },
    computed: {
        userInfo() {
            return this.$store.state.user.userInfo;
        }
    },
    watch: {
        userInfo(newVal, oldVal) {
            // console.log(`userInfo changed from ${oldVal} to ${newVal}`);
            this.userInfoDetail = newVal ? newVal : {}
            // 在这里执行你的逻辑
        }
    },
    created() {
        this.conversationsM()
    },
    methods: {
        openNewChat() {
            if (this.dialogueList) {
                // 当前有聊天内容时添加新聊天
                this.dialogueList = []
                this.conversationId = ''
                this.taskId = ''
                if (this.thinkingTime) {
                    clearInterval(this.thinkingTime)
                }
                this.pushTextKey = 'answerThink'
                this.stopMessages()
            }
        },
        // 删除历史单条
        handleDelete(item) {
            this.$confirm('删除后，该对话将不可恢复。确认删除吗？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                // type: 'warning',
                center: true
            }).then(() => {
                toolBox.deleteMessages(item.id).then(val => {
                    if (val.code == 200) {
                        this.conversationsM()
                    }
                })
            }).catch(() => {
            });
        },
        // 查询历史单条
        clickHistoryItem(item) {
            toolBox.getMessagesItem(item.id).then(val => {
                if (val.code == 200) {
                    this.conversationId = item.id
                    this.dialogueList = []
                    let dataList = JSON.parse(val.msg).data
                    for (var i in dataList) {
                        this.dialogueList.push({
                            query: dataList[i].query,
                            answerThink: dataList[i].answer.split('\n\n\n\n')[0],
                            answerText: dataList[i].answer.split('\n\n\n\n')[1],
                            collapseValue: []
                        })
                    }
                }
            })
        },
        // 查询历史聊天列表
        conversationsM() {
            toolBox.conversations().then(val => {
                console.log(val)
                if (val.code == 200) {
                    // console.log(JSON.parse(val.msg).data)
                    this.historyList = JSON.parse(val.msg).data ? JSON.parse(val.msg).data : []
                }
            })
        },
        setThinkingTime() {
            let that = this
            if (that.thinkingTime) {
                clearInterval(that.thinkingTime)
            }
            this.thinkingTime = setInterval(() => {
                if (this.thinking == '思考中.....') {
                    this.thinking = '思考中'
                }
                this.thinking = this.thinking + '.'
            }, 300)
        },
        // 停止生成方案
        stopMessages() {
            // 当前存在可结束会话
            if (this.taskId) {
                toolBox.stopMessages(this.taskId).then(val => {
                    if (val.code == 200) {
                        this.taskId = ''//置空可结束会话
                        this.loading = false
                        if (this.thinkingTime) {
                            clearInterval(this.thinkingTime)
                        }
                        this.pushTextKey = 'answerThink'
                        this.dialogueList[this.dialogueList.length - 1].answerText = '已停止生成......'
                        this.dialogueList[this.dialogueList.length - 1].collapseValue = []
                    }
                })
            }
        },
        // 生成方案
        sendChat() {
            let that = this

            toolBox.agentCheckSupport(
                {
                    appCode: "DEEP_SEEK_R1_673B",
                }).then(val => {
                    if (val.code == 200) {
                        // 生成方案的逻辑
                        if (this.sendValue && !this.loading) {

                            this.loading = true
                            this.controller = new AbortController() // 终止or结束会话，做了个全局的...
                            fetchEventSource(process.env.VUE_APP_BASE_API + '/api/agent/chat-messages', {
                                method: 'POST',
                                headers: {
                                    'Content-Type': 'application/json',
                                    'Accept': '*/*',
                                    'Authorization': 'Bearer ' + getToken(),
                                },

                                body: JSON.stringify(
                                    {
                                        inputs: {},
                                        appCode: "DEEP_SEEK_R1_673B",
                                        query: this.sendValue,
                                        conversation_id: this.conversationId ? this.conversationId : '',
                                        user: this.userInfoDetail.userName
                                    }
                                ),
                                openWhenHidden: true,
                                signal: this.controller.signal,
                                onmessage: (msg) => {
                                    // console.log('SSE会在通过事件源收到数据时触发')
                                    console.log('接口返回', JSON.parse(msg.data))
                                    const msgData = JSON.parse(msg.data)
                                    //我这里是判断我请求回来的数据里是否包含'[DONE]'，他是数组里的最后一项，表示加载完成
                                    if (!msgData.event.includes('node_finished')) {
                                        // const data = JSON.parse(msg.data)
                                        // const text = msgData.data.text
                                        // const percent = msgData.percent
                                        if (msgData.event === 'node_started') {
                                            // 连接成功，开始检测逻辑
                                            this.progressDone = true
                                            // this.progressValue = 0
                                            // this.progressTxt = '数据检查中，该过程可能需要一段时间，请勿关闭窗口'

                                            // this.getTurnCheck()
                                            return false
                                        }
                                        // console.log(msgData);
                                        const message = msgData.answer
                                        //定时器，控制进度条和文字的展示速度
                                        this.speed += 300
                                        // this.timer = setTimeout(() => {
                                        if (message) {
                                            if (this.conversationId != msgData.conversation_id) {
                                                this.conversationId = msgData.conversation_id
                                            }
                                            if (this.taskId != msgData.task_id) {
                                                this.taskId = msgData.task_id
                                            }
                                            this.dialogueList[this.dialogueList.length - 1][this.pushTextKey] = this.dialogueList[this.dialogueList.length - 1][this.pushTextKey] + message
                                            if (message == '\n\n\n\n') {
                                                this.dialogueList[this.dialogueList.length - 1].collapseValue = []
                                                this.pushTextKey = 'answerText'
                                            }
                                            document.getElementsByClassName('chatContentBox')[0].scrollTop = document.getElementsByClassName('chatContent')[0].scrollHeight

                                            // console.log(message)
                                            // this.progressDone = false
                                            // console.log(message=='\n\n\n\n')
                                            // console.log(msgData.from_variable_selector);
                                            // this.progressTxt = this.progressTxt.replace(/<p>|<\/p>/g, '') + message
                                            // this.progressTxt = this.progressTxt + message
                                            // this.simplemde.value(this.progressTxt);
                                            // document.getElementsByClassName('CodeMirror-scroll')[0].scrollTop = document.getElementsByClassName('CodeMirror-sizer')[0].scrollHeight
                                            // this.simplemde.togglePreview()

                                            // setTimeout(() => {
                                            //     this.progressTxt
                                            // },1000)

                                            // this.progressTxt = this.progressTxt + message
                                        }
                                        // this.progressValue = Number(percent)
                                        // if (!this.progressDone) {

                                        //     this.stopSSE()
                                        // }
                                        // }, this.speed)
                                    }
                                    // console.log(msgData.event);
                                    // if (msgData.event.includes('workflow_finished')) {
                                    //     this.simplemde.togglePreview()

                                    // }

                                },
                                onclose: (val) => {
                                    console.log('connection closed')
                                    this.loading = false
                                    if (this.thinkingTime) {
                                        clearInterval(this.thinkingTime)
                                    }
                                    this.pushTextKey = 'answerThink'
                                    this.agentSupport().then(val => {
                                        this.$store.dispatch("setFreeTimes", val.msg)
                                    })
                                },
                                onerror: (err) => {
                                    this.loading = false
                                    console.log('err')
                                    console.log(err)
                                    if (this.thinkingTime) {
                                        clearInterval(this.thinkingTime)
                                    }
                                },
                                onopen: (response) => {
                                    this.loading = true
                                    console.log(response)
                                    console.log('responseonopen')
                                    this.setThinkingTime()
                                    let snap = {
                                        query: this.sendValue,
                                        answerThink: '',
                                        answerText: '',
                                        collapseValue: ['think' + Number(this.dialogueList.length)]
                                    }
                                    // let snapList = [
                                    //     {
                                    //         type: 'R',
                                    //         text: this.sendValue
                                    //     },
                                    //     {
                                    //         type: 'L',
                                    //         text: '',
                                    //         think: '',
                                    //         collapseValue: 'think' + Number(this.dialogueList.length + 1)
                                    //     }
                                    // ]
                                    // this.dialogueList = this.dialogueList.concat(snapList)
                                    this.dialogueList.push(snap)
                                    this.sendValue = ''
                                    return Promise.resolve()
                                }
                            })
                        }
                        else {
                            if (!this.loading) {
                                this.$modal.msgWarning("请输入内容");
                            }
                        }
                    }
                }).catch(err => {
                    console.log(err)
                })
        },
        getTurnCheck() {

        },
        goBack() {
            this.$router.replace({ path: '/' });
        },
        handleKeyCode(event) {
            console.log(event);
            if (event.keyCode == 13) {
                if (!event.shiftKey) {
                    this.sendChat()
                } else {
                    this.sendValue += "\n";
                }
            }
        }
    },
    beforeDestroy() {
        if (this.thinkingTime !== null) {
            clearInterval(this.thinkingTime)
            this.thinkingTime = null; // 将引用设置为 null，避免内存泄漏
        }
    }
};
</script>

<style lang="scss" scoped>
.chat {
    width: 100vw;
    min-width: 1000px;
    background-color: #fff;
    display: flex;
    overflow: hidden;
    height: 100vh;
    .leftHistorybox {
        width: 260px;
        background-color: #2b2a2c;
        padding: 20px;
        .newChatBtn {
            background-color: #3e3e3e;
            border-radius: 5px;
            border: #5c5c5c solid 2px;
            padding: 10px;
            text-align: center;
            color: rgb(255, 255, 255);
            cursor: pointer;
            i {
                margin-right: 5px;
            }
        }
        .newChatBtn:hover {
            background-color: #5f5e5e;
        }
        .date {
            color: #999;
            margin: 15px 0;
            font-size: 14px;
        }
        .chatBox {
            margin-top: 15px;
            overflow-y: scroll;
            height: calc(100vh - 60px - 100px);
            padding-right: 8px;
        } /*定义滚动条轨道 宽度*/
        ::-webkit-scrollbar {
            width: 5px;
            height: 5px;
        }
        /*定义滚动条轨道 内阴影+圆角*/
        ::-webkit-scrollbar-track {
            border-radius: 5px;
            background-color: rgba(0, 0, 0, 0.05);
        }
        /*定义滑块 内阴影+圆角*/
        ::-webkit-scrollbar-thumb {
            border-radius: 5px;
            background-color: rgba(169, 169, 169, 0.25);
        }
        .chatItemActive {
            background-color: #b4b4b4 !important;
            color: #000 !important;
        }
        .chatItem {
            background-color: #454849;
            border-radius: 5px;
            padding: 10px;
            border-radius: 5px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            color: rgb(255, 255, 255);
            font-size: 14px;
            margin-bottom: 10px;
            cursor: pointer;
            div {
                display: flex;
                align-items: center;
                i {
                    margin-right: 5px;
                }
            }
            .name {
                display: -webkit-box; /* 设置为WebKit内核的弹性盒子模型 */
                -webkit-box-orient: vertical; /* 垂直排列 */
                -webkit-line-clamp: 1; /* 限制显示两行 */
                overflow: hidden; /* 隐藏超出范围的内容 */
                text-overflow: ellipsis; /* 使用省略号 */
            }
            .action {
                margin-left: 5px;
                cursor: pointer;
            }
        }
    }
    .main-content {
        border-right: 1px solid #e0e0e0;
        width: calc(100% - 260px);
        .titleR1 {
            width: 100%;
            height: 60px;
            display: flex;
            align-items: center;
            justify-content: center;
            text-align: center;
            border-bottom: 1px solid #e0e0e0;
            div:nth-child(2) {
                // color: #ff0000;
            }
            div:nth-child(3) {
                color: #767676;
                font-size: 14px;
                padding-top: 10px;
            }
        }
        .typeArea {
            min-width: 500px;
            max-width: 1000px;
            height: 100%;
            margin: 0 auto;
        }
        .chatContentBox {
            // width: 100%;
            margin: 0 auto;
            height: calc(100vh - 60px - 60px - 100px);
            padding: 30px 0;
            overflow-y: scroll;
            font-size: 12px;
            .rightBox {
                display: flex;
                justify-content: end;
                .via {
                    width: 40px;
                    height: 40px;
                    border-radius: 50%;
                }
                .contentBox {
                    margin-right: 10px;
                    position: relative;
                    color: #000;
                    padding: 10px 20px;
                    line-height: 1.2;
                    text-align: center;
                    border: 1px solid #a2cffc;
                    border-radius: 5px;
                    background: #a2cffc;
                    height: fit-content;
                }
                //     .contentBox::after {
                //         content: "";
                //         position: absolute;
                //         width: 0;
                //         height: 0;
                //         /* 箭头靠右边 */
                //         top: 10px;
                //         right: -10px;
                //         border-top: 10px solid transparent;
                //         border-bottom: 10px solid transparent;
                //         border-left: 10px solid #a2cffc;
                //         /* 箭头靠下边 */
                //         /* left: 25px;
                // bottom: -10px;
                // border-left: 10px solid transparent;
                // border-right: 10px solid transparent;
                // border-top: 10px solid teal; */
                //         /* 箭头靠左边 */
                //         /* top: 13px;
                // left: -10px;
                // border-top: 10px solid transparent;
                // border-bottom: 10px solid transparent;
                // border-right: 10px solid teal; */
                //         /* 箭头靠下边 */
                //         /* top: -10px;
                // left: 25px;
                // border-left: 10px solid transparent;
                // border-right: 10px solid transparent;
                // border-bottom: 10px solid teal; */
                //     }
            }
            .leftBox {
                margin: 20px 0;
                display: flex;
                ::v-deep .el-collapse {
                    border-top: none !important;
                }
                .via {
                    width: 40px;
                    height: 40px;
                }
                .contentBox {
                    width: 90%;
                    margin-left: 10px;
                    position: relative;
                    // color: #fff;
                    padding: 10px 20px;
                    line-height: 1.2;
                    text-align: left;
                    box-shadow: 0px 0px 2px 0px rgba(0, 0, 0, 0.15);
                    border-radius: 5px;
                    // background: #a2cffc;
                    height: fit-content;
                }
                //     .contentBox::after {
                //         content: "";
                //         position: absolute;
                //         width: 0;
                //         height: 0;
                //         /* 箭头靠左边 */
                //         top: 13px;
                // left: -10px;
                // border-top: 10px solid transparent;
                // border-bottom: 10px solid transparent;
                // border-right: 10px solid rgb(255, 255, 255);
                //     }
            }
        }
        ::-webkit-scrollbar {
            width: 0;
        }
        .inputSendBox {
            background: #fff;
            height: 100px;
            // width: 100%;
            margin: 0 auto;
            padding: 10px 0;
            // border-top: 1px solid #e0e0e0;

            .inputBox {
                margin: 0 auto;
                width: 100%;
                position: relative;
                height: 60px;
                ::v-deep input {
                    // width: 100%;
                    padding: 2rem 1.5rem;
                    border: none;
                    border-radius: 10px;
                    font-size: 1rem;
                    background: #fff;
                    backdrop-filter: blur(10px);
                    box-shadow: 0px 0px 5px 0px rgba(0, 0, 0, 0.15);
                    transition: all 0.3s ease;
                    resize: none !important;
                }
                .el-textarea {
                    height: 60px !important;
                    resize: none;
                    box-shadow: 0px 0px 5px 0px rgba(0, 0, 0, 0.15);
                    ::v-deep .el-textarea__inner {
                        height: 100%;
                        resize: none !important;
                    }
                    ::v-deep .el-textarea__inner {
                        overflow: auto; /* 需要滚动条时允许滚动 */
                        scrollbar-width: none; /* 对于Firefox */
                    }
                    ::v-deep .el-textarea__inner::-webkit-scrollbar {
                        display: none;
                    }
                    ::v-deep .el-textarea__inner {
                        -ms-overflow-style: none; /* IE 10+ */
                    }
                }
                .btn {
                    position: absolute;
                    right: 20px;
                    top: 15px;
                    cursor: pointer;

                    img {
                        height: 30px;
                        margin-left: 10px;
                    }
                    // width: 150px;
                    // border-radius: 200px;
                    // background-color: #2563eb;
                    // display: flex;
                    // justify-content: center;
                    // align-items: center;
                    // color: #fff;
                    // cursor: pointer;
                    // height: ;
                }
            }
        }
    }
}
</style>